package com.oasistudio.tk.connector.imp;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.oasistudio.tk.connector.TopAPIConnectorHelper;
import com.oasistudio.tk.connector.TopApiRequest;
import com.oasistudio.tk.connector.TopApiResponse;
import com.taobao.tbw.common.TBWContext;

public class ItemsListConnector implements TopAPIConnectorHelper {
	private String itemIds;//???20�??�??�?d�??,???
	private String fields="detail_url,num_iid,title,pic_url,num,location,price,post_fee,express_fee,ems_fee,freight_payer";//�??????��????

	public ItemsListConnector() {
	}

	public void setItemIds(String itemIds){
		this.itemIds = itemIds;
	}

	public void setFields(String fields){
		this.fields = fields;
	}

	@Override
	public Object asyncPaser(byte[] part) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getApiUrl() {
		TopApiRequest request = new TopApiRequest();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		TreeMap<String, String> params = new TreeMap<String, String>();
		//???系�????
		params.put("method", "taobao.items.list.get");
		params.put("session", TBWContext.getInstance().getTopsession());
		params.put("timestamp", sdf.format(calendar.getTime()));
		params.put("format", "json");
		params.put("app_key", TBWContext.getInstance().getAppKey());
		params.put("v", "2.0");
		params.put("partner_id", "top-apitools");
		params.put("sign_method", "md5");
		//API method ???
		params.put("fields", fields);
		params.put("num_iids", itemIds);//???id??���???��??��?�??�??�?0�?		
		request.params = params;
		String url = request.generalRequestUrl(true);
		System.out.println("ItemListConnector.getApiUrl() url = "+url);
		return url;
	}

	/**
	 * �??�?????�???��? total_results Number ??��?��?交�?信�??��? trades Trade[] 交�?信�???��
	 * hash_next Boolean ??��???�?��
	 */
	@Override
	public Object syncPaser(byte[] all) {
		ItemsInfo itemsInfo = new ItemsInfo();
		try {
			TopApiResponse response = new TopApiResponse("items_list_get_response");
			String str = new String(all, "UTF-8");
			//Log.d("return msg:", str);
			if (response.parseResult(str).success) {
				itemsInfo.isSuccess = true;
				JSONObject jsObj = response.data;
				if (jsObj.has("items")) {
					JSONObject itemsJSON = jsObj.getJSONObject("items");
					if (itemsJSON.has("item")) {
						JSONArray itemsArray = itemsJSON.getJSONArray("item");
						Item[] items = new Item[itemsArray.length()];
						itemsInfo.items = items;
						for (int i = 0; i < itemsArray.length(); i++) {
							JSONObject trade = itemsArray.getJSONObject(i);
							items[i] = new Item();
							items[i].num_iid = trade.optLong("num_iid");
							items[i].num = trade.optLong("num");
							items[i].title = trade.optString("title");
							items[i].detail_url = trade.optString("detail_url");
							items[i].pic_url = trade.optString("pic_url");
							items[i].price = trade.optString("price");
							Location location = new Location();
							location.state = trade.optJSONObject("location").optString("state");
							location.city = trade.optJSONObject("location").optString("city");
							items[i].location = location;
						}
					}
				}
			} else {
				itemsInfo.isSuccess = false;
				itemsInfo.errCode = response.errCode;
				itemsInfo.errInfo = response.errInfo;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return itemsInfo;
	}

	public static class ItemsInfo {
		public String errCode;
		public String errInfo;
		public Boolean isSuccess;
		public Item[] items;//?��????�?	
	}

	public static class Item {
		public String detail_url;//???�??页�??��?
		public Number num_iid;//????��?ID
		public String title;//?????��
		public String pic_url;//???主�???		
		public Number num;//????��?
		public Location location;//????????		
		public String price;//???价�?�??�??5.00�??�?????精确?��???		
		public String post_fee;//平�?
		public String express_fee;//�??
		public String ems_fee;//EMS
		public String freight_payer;//�?��?��??��?,seller�??家�????�?uyer(买�??��?�?		
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("num_iid:"+num_iid);
			sb.append(";title:"+title);
			sb.append(";num:"+num);
			sb.append(";price:"+price);
			return sb.toString();
		}
	}
	
	public static class Location{
		public String state;
		public String city;
		
		public String toString(){
			return state+" "+city;
		}
	}
}
